from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer as Serializer
from django.conf import settings

# 从settings中获取令牌过期时间（建议在settings.py中定义）
ACCESS_TOKEN_EXPIRES = getattr(settings, 'ACCESS_TOKEN_EXPIRES', 60 * 60)  # 默认1小时


def generate_access_token(openid: str) -> str:
    """
    生成签名的OpenID令牌

    :param openid: 用户的OpenID（字符串类型）
    :return: 签名后的令牌字符串
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=ACCESS_TOKEN_EXPIRES)
    data = {'openid': openid}
    token = serializer.dumps(data)
    return token.decode()


def check_access_token(access_token: str) -> str or None:
    """
    解析并验证签名的OpenID令牌

    :param access_token: 签名的令牌字符串
    :return: 解析出的OpenID字符串，验证失败返回None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=ACCESS_TOKEN_EXPIRES)
    try:
        data = serializer.loads(access_token)
    except (BadData, SignatureExpired):
        return None
    else:
        return data.get('openid')